/**
 * Created by Administrator on 2019-01-22.
 */
import { useAppStore } from "@/store/app";
import appUtils from '@/utils/util'

export default {
  myImage: '#',
  morenAvatar: 'moren.png',
  endpoint: '#',
  accessKeyId: '#',
  accessKeySecret: '#',
  bucket: '#',
  avatarImg: 'avatar/',
  windowImg: 'window/',
  digitImg: 'digitImg/',
  xiurenImg: 'xiuren/',
}

// 时间格式化
export const formatDate = (date, fmt) => {
  date = new Date(Date.parse(date))
  const o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'S': date.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt
}

export function replaceFun(str, f, e) {
  let reg = new RegExp(f, 'g')// g,表示全部替换。
  return str.replace(reg, e)
}

/*
 * 参数说明：
 * number：要格式化的数字
 * decimals：保留几位小数
 * dec_point：小数点符号
 * thousands_sep：千分位符号
 * */
export const moneyFormat = (number, decimals) => {
  let dec_point = '.'
  let thousands_sep = ','
  number = (number + '').replace(/[^0-9+-Ee.]/g, '')
  let roundtag = roundtag || 'ceil' // "ceil","floor","round"
  let n = !isFinite(+number) ? 0 : +number
  let prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
  let sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep
  let dec = (typeof dec_point === 'undefined') ? '.' : dec_point
  let s
  let toFixedFix = function (n, prec) {
    let k = Math.pow(10, prec)
    return '' + parseFloat(Math[roundtag](parseFloat((n * k).toFixed(prec * 2))).toFixed(prec * 2)) / k
  }
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
  let re = /(-?\d+)(\d{3})/
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, '$1' + sep + '$2')
  }
  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }
  return s.join(dec)
}

export function ossPut(file, path) {
  // let OSS = require('ali-oss')
  const client = new OSS({
    endpoint: appUtils.endpoint,
    accessKeyId: appUtils.accessKeyId,
    accessKeySecret: appUtils.accessKeySecret,
    bucket: appUtils.bucket
  })
  let filename = file.name
  let eg = randomString()
  let index1 = filename.lastIndexOf('.')
  let index2 = filename.length
  let ext = filename.substring(index1 + 1, index2)// 后缀名
  let fileName = formatDate(new Date(), 'yyyyMMddhhmmss') + Math.round(Math.random() * 100) + eg + '.' + ext
  let uploadPath = path + fileName

  async function put() {
    try {
      const result = await client.put(uploadPath, file)
      state.state.user.ossUploadObject = result.url
      state.state.user.coverUpload = result
      return filename
    } catch (e) {
      console.log(e)
      return 'false'
    }
  }

  put()
  return fileName
}

export function ossMp4Put(file, path) {
  const client = new OSS({
    endpoint: appUtils.endpoint,
    accessKeyId: appUtils.accessKeyId,
    accessKeySecret: appUtils.accessKeySecret,
    bucket: appUtils.bucket
  })
  let filename = file.name
  let eg = randomString()
  let index1 = filename.lastIndexOf('.')
  let index2 = filename.length
  let ext = filename.substring(index1 + 1, index2)// 后缀名
  let fileName = formatDate(new Date(), 'yyyyMMddhhmmss') + Math.round(Math.random() * 100) + eg + '.' + ext
  let uploadPath = path + fileName

  async function put() {
    try {
      const result = await client.multipartUpload(uploadPath, file, {
        progress: (p) => {
          state.state.uploadProgress = Math.floor(p * 100);
          state.state.user.uploadProgress = Math.floor(p * 100);
        }
      })
      state.state.user.ossUploadObject = result.url
      state.state.user.coverUpload = result
      return filename
    } catch (e) {
      console.log(e)
      return 'false'
    }
  }

  put()
  return fileName
}

export function randomString() {
  let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  /** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  let maxPos = $chars.length
  let pwd = ''
  for (let i = 0; i < 3; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

/**
 * 判断对象非空
 * */
export const isBlank = (objce) => {
  return objce === null || objce === '' || isFlag(objce, 'undefined') || isFlag(objce, 'null') || isFlag(JSON.stringify(objce), '{}') || isFlag(
    JSON.stringify(objce),
    '[]');
}

/**
 * 判断对象是否相等
 * */
export const isFlag = (object, value) => {
  return object === value || JSON.stringify(object) === value || encodeURIComponent(object) === encodeURIComponent(value);
}

/**
 * 按key升序排序，返回数组
 * */
export function sortByKey(array, key) {
  return array.sort(function (a, b) {
    let x = a[key]
    let y = b[key]
    return ((x < y) ? -1 : ((x < y) ? 1 : 0))
  })
}

export function ossVideoUpload() {
  let limit = state.state.uploadLimit - state.state.ossUploading.length// 获取正在上传列表还缺多少条上传记录
  for (let i = 0; i < limit; i++) { // 循环加入上传数据
    if (state.state.ossUpload.length > 0) {
      // let fileUpload =state.state.ossUpload[0];
      // fileUpload.status=true;
      state.state.ossUploading.push(state.state.ossUpload[0])// 把数据放在正在上传队列中
      state.state.ossUpload.splice(0, 1)// 从上传队列这删除
    }
  }
  for (let i = 0; i < state.state.ossUploading.length; i++) { // 循环更新上传数据
    if (!state.state.ossUploading[i].status) { // 判断上传状态 如果没有上传 就调用上传方法
      state.state.ossUploading[i].fileName = ossMultipartUpload(state.state.ossUploading[i].file, state.state.uploadPath)
    }
  }
}

// 缓存数据初始化
export function initCacheData() {
  state.state.coverUrl = ''
  state.state.coverUpload = {}
  state.state.pictureOneUrl = ''
  state.state.pictureOneUpload = {}
  state.state.pictureUrl = ''
  state.state.pictureUpload = {}
  state.state.coverOneUrl = ''
  state.state.coverOneUpload = {}
  state.state.avatarUrl = ''
  state.state.avatarUpload = {}
  state.state.avatarOneUrl = ''
  state.state.avatarOneUpload = {}
  state.state.uploadShow = false
  state.state.requestUrls = ''
  state.state.uploadPath = ''
  state.state.fileList = []
  state.state.ossUpload = []
  state.state.ossVideoCoverTemp = []
  state.state.ossVideoCover = []
  state.state.ossUploading = []
  state.state.detailsUploadList = []
  state.state.mp3FileUploadList = []
  state.state.videoUploadList = []
  state.state.coverUploadList = []
  state.state.videoFileList = []
  state.state.videoListUpload = []
  state.state.videoUpload = {}
  state.state.uploadStatus = false
  state.state.uploadShow = false
  state.state.renovateFlag = false
  state.state.initDataFlag = true
  state.state.unitList = [{
    value: '米',
    label: '米'
  }, {
    value: '㎡',
    label: '㎡'
  }, {
    value: '套',
    label: '套'
  }]
}

/**
 * 计算上传进度
 * */
export function stateOssUploadSpeed(name, p) {
  p = (parseInt(p * 100) / 100).toFixed(2)
  const ossUpload = state.state.ossUploading
  for (let i = 0; i < ossUpload.length; i++) {
    // ossUpload[i].fileName=ossUpload[i].fileName.replace(/[&\|\\\*^%$#@\-\+\（\）\~\ ]/g, "");//去掉特殊符号
    if (ossUpload[i].fileName === name) {
      ossUpload[i].percent = parseInt(p * 100)
      ossUpload[i].status = true
      if (ossUpload[i].percent === 100) {
        ossUpload[i].file = ''
        state.state.ossVideoCover.push(ossUpload[i])
        ossUpload.splice(i, 1)
        ossVideoUpload()
      }
    }
  }
}

export function ossMultipartUpload(file, path) {
  // let OSS = require('ali-oss')
  const client = new OSS({
    endpoint: appUtils.endpoint,
    accessKeyId: appUtils.accessKeyId,
    accessKeySecret: appUtils.accessKeySecret,
    bucket: appUtils.bucket
  })
  // let c=file.name.replace(/[&\|\\\*^%$#@\-]/g,"");
  let filename1 = file.name.replace(/[&|\\*^%$#@\-+（）~ ]/g, '')// 去掉特殊符号
  let filename = filename1.replace(/[\u4e00-\u9fa5]/g, '')// 去掉特殊符号
  let index1 = filename.lastIndexOf('.')
  let index2 = filename.length
  let ext = filename.substring(index1 + 1, index2)// 后缀名
  // let fileName = filename
  let fileName = formatDate(new Date(), 'yyyyMMddhhmmss') + Math.round(Math.random() * 100) + filename
  let uploadPath = path + fileName

  async function multipartUpload() {
    try {
      const result = await client.multipartUpload(uploadPath, file, {
        progress,
        meta: {
          year: 2017,
          people: 'test'
        }
      })
      const head = await client.head(uploadPath)
      console.log('uploadPath', uploadPath)
      console.log('fileName', fileName)
      let ossObjct = {}
      console.log('head.res.requestUrls', head.res.requestUrls)
      ossObjct.fileName = fileName
      state.state.ossVideoCoverTemp.push(ossObjct)
      if (state.state.ossUploading.length === 0) {
        state.state.uploadStatus = false
        state.state.uploadShow = false
      }
      let index1 = result.name.lastIndexOf('.')
      let index2 = result.name.length
      let ext = result.name.substring(index1 + 1, index2)// 后缀名
      if (ext === 'mp4') {
        state.state.requestUrls = head.res.requestUrls + '?x-oss-process=video/snapshot,t_1000,f_jpg,w_800,h_600&compress'
      }
    } catch (e) {
      // 捕获超时异常
      if (e.code === 'ConnectionTimeoutError') {
        console.log('Woops,超时啦!')
        // do ConnectionTimeoutError operation
      }
    }
  }

  const progress = async function (p) {
    stateOssUploadSpeed(fileName, p)
    // console.log("p:" + p);
  }
  multipartUpload()
  return fileName
}

export function stateOssUpload(name) {
  const ossUpload = JSON.parse(JSON.stringify(state.state.ossUpload))
  for (let i = 0; i < ossUpload.length; i++) {
    if (ossUpload[i].fileName === name) {
      ossUpload[i].status = true
    }
  }
  state.state.ossUpload = ossUpload
}

export function accessFlag(access) {
  return state.state.user.access.indexOf(access) !== -1;
}

export function exportExcelUtil(data, fileName) {
  const link = document.createElement('a')
  const blob = new Blob([data], {type: 'application/vnd.ms-excel'})
  link.style.display = 'none'
  link.href = URL.createObjectURL(blob)
  link.setAttribute('download', fileName + `.xls`)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

export function getImageInfo(url, callback) {
  let img = new Image()
  img.src = url
  if (img.complete) {
    // 如果图片被缓存，则直接返回缓存数据
    callback(img.width, img.height)
  } else {
    img.onload = function () {
      callback(img.width, img.height)
    }
  }
  return img
}

export function getImages(_url) {
  if (_url !== undefined) {
    const _u = _url.substring(7)
    return 'https://images.weserv.nl/?url=' + _u
  }
}

// 不常用特定条件上传
export function ossPutForGif(file, path) {
  path = 'icon/'
  // let OSS = require('ali-oss')
  const client = new OSS({
    endpoint: appUtils.endpoint,
    accessKeyId: appUtils.accessKeyId,
    accessKeySecret: appUtils.accessKeySecret,
    bucket: appUtils.bucket
  })
  let filename = '745.gif'
  // let filename = file.name
  // let index1 = filename.lastIndexOf('.')
  // let index2 = filename.length
  // let ext = filename.substring(index1 + 1, index2)// 后缀名
  // let fileName = formatDate(new Date(), 'yyyyMMddhhmmss') + Math.round(Math.random() * 100) + '.' + ext
  let uploadPath = path + filename

  async function put() {
    try {
      const result = await client.put(uploadPath, file)
      state.state.user.ossUploadObject = result.url
      state.state.user.coverUpload = result
      return filename
    } catch (e) {
      console.log(e)
      return 'false'
    }
  }

  put()
  return filename
}

// 不常用特定条件上传
export function ossPutForRoom(file, path) {
  path = 'icon/'
  let filename = '0725home_bg_whcus.png'
  // let OSS = require('ali-oss')
  const client = new OSS({
    endpoint: appUtils.endpoint,
    accessKeyId: appUtils.accessKeyId,
    accessKeySecret: appUtils.accessKeySecret,
    bucket: appUtils.bucket
  })
  // let filename = file.name
  // let index1 = filename.lastIndexOf('.')
  // let index2 = filename.length
  // let ext = filename.substring(index1 + 1, index2)// 后缀名
  // let fileName = formatDate(new Date(), 'yyyyMMddhhmmss') + Math.round(Math.random() * 100) + '.' + ext
  let uploadPath = path + filename

  async function put() {
    try {
      const result = await client.put(uploadPath, file)
      state.state.user.ossUploadObject = result.url
      state.state.user.coverUpload = result
      return filename
    } catch (e) {
      console.log(e)
      return 'false'
    }
  }

  put()
  return filename
}

/**
 * 分片图片上传  开始
 * */
export function ossMultipartImageUpload(file, path, fileName) {
  // let OSS = require('ali-oss')
  const client = new OSS({
    endpoint: appUtils.endpoint,
    accessKeyId: appUtils.accessKeyId,
    accessKeySecret: appUtils.accessKeySecret,
    bucket: appUtils.bucket
  })
  let uploadPath = path + fileName

  async function multipartImageUpload() {
    try {
      const result = await client.multipartUpload(uploadPath, file, {
        progress,
        meta: {
          year: 2017,
          people: 'test'
        }
      })
      const head = await client.head(uploadPath)
      let ossObjct = {}
      ossObjct.fileName = head.res.requestUrls
      state.state.ossVideoCoverTemp.push(ossObjct)
      if (state.state.ossUploading.length === 0) {
        state.state.uploadStatus = false
        state.state.uploadShow = false
      }
    } catch (e) {
      // 捕获超时异常
      if (e.code === 'ConnectionTimeoutError') {
        console.log('Woops,超时啦!')
        // do ConnectionTimeoutError operation
      }
      console.log(e)
    }
  }

  const progress = async function (p) {
    stateOssImageUploadSpeed(fileName, p)
    // console.log("p:" + p);
  }
  multipartImageUpload()
  return fileName
}

/**
 * 计算上传进度
 * */
export function stateOssImageUploadSpeed(name, p) {
  p = (parseInt(p * 100) / 100).toFixed(2)
  const ossUpload = state.state.ossUploading
  for (let i = 0; i < ossUpload.length; i++) {
    // ossUpload[i].fileName=ossUpload[i].fileName.replace(/[&\|\\\*^%$#@\-\+\（\）\~\ ]/g, "");//去掉特殊符号
    if (ossUpload[i].fileName === name) {
      ossUpload[i].percent = parseInt(p * 100)
      ossUpload[i].status = true
      if (ossUpload[i].percent === 100) {
        ossUpload[i].file = ''
        state.state.ossVideoCover.push(ossUpload[i])
        ossUpload.splice(i, 1)
        ossImageUpload()
      }
    }
  }
}

/**
 * 启动上传方法列队
 * */
export function ossImageUpload() {
  if (isFlag(state.state.ossUpload.length, 0) && isFlag(state.state.ossUploading.length, 0)) { // 如果等待上传和正在上传的长度为0就意味着没有上传
    state.state.uploadStatus = false
    return
  }
  let limit = state.state.uploadLimit - state.state.ossUploading.length// 获取正在上传列表还缺多少条上传记录
  for (let i = 0; i < limit; i++) { // 循环加入上传数据
    if (state.state.ossUpload.length > 0) {
      state.state.ossUploading.push(state.state.ossUpload[0])// 把数据放在正在上传队列中
      state.state.ossUpload.splice(0, 1)// 从上传队列这删除
    }
  }
  for (let i = 0; i < state.state.ossUploading.length; i++) { // 循环更新上传数据
    if (!state.state.ossUploading[i].status) { // 判断上传状态 如果没有上传 就调用上传方法
      state.state.ossUploading[i].fileName = ossMultipartImageUpload(state.state.ossUploading[i].file, state.state.ossUploading[i].path,
        state.state.ossUploading[i].fileName)
    }
  }
}

/**
 * 准备图片数据方法，存放在上传队列中。取得名字用来提交到后台
 * */
export function handleBeforeImageUpload(file, path) {
  let filename1 = file.name.replace(/[&|\\*^%$#@\-+（）~ ]/g, '')// 去掉特殊符号
  let filename = filename1.replace(/[\u4e00-\u9fa5]/g, '')// 去掉特殊符号

  let fileName = formatDate(new Date(), 'yyyyMMddhhmmssS') + Math.round(Math.random() * 1000) + filename
  let ossObjct = {}
  ossObjct.name = fileName
  ossObjct.fileName = fileName
  ossObjct.percent = 0
  ossObjct.path = path
  ossObjct.status = false
  // file.name=fileName;
  ossObjct.file = file
  state.state.ossUpload.push(ossObjct)
  // this.$store.state.uploadShow = true
  return fileName
}

/**
 * 分片图片上传  结束
 * */
